#! /usr/bin/perl

#use the HMTLSubs and DB package
use HTMLSubs;
use DBQueries;

#also enable strict mode
use strict;

#use the md5 package to get the md5 version of the password
use Digest::MD5 qw(md5 md5_hex md5_base64);

#the username of the individual that forgot the password will be passed to this script via get by teh script callign it
#start by obtaining the username
my $input = obtain_input();


#now determine if a user has submitted change password request
if($input =~ m/username=.*/){
	
	#declare username
	$input =~ m/username=(.*)/;
	
	my $username = $1;
	
	#ensure that the person is a user
	if(DBQueries::isUser($username)){
		
		#call subroutine to reset password to 8 random characters and email user
		regenerate_password($username);

		#call sub to show success
		show_success();
	}
	#otherwise show submission again
	else{
		
		my $error_text = "<font color=\"red\">Invalid Username!</font>";
		
		print_submission_form($error_text);
	}
	
}
#otherwise show username submission
else{
	
	print_submission_form();
}

#sub to print the submission form for a new password
sub print_submission_form{
	
	#obtain potential error text
	my $error_text = $_[0];
	
	#print submission
	
	#call subroutine to generate html beginning
	HTMLSubs -> generate_html_beginning("Reset Password");
	
	print <<END_HTML;
	<div class="header">

	<div class="titles">
	<h1>Document Management System</h1>
	</div><!--titles-->

	<h2>Reset Password</h2>

	<h3>You can reset your password here</h3>

	<table class="tableheader">
	<tr class="trheader">
	<td class="tdheaderleft">
	<p>0 Files (Access 0 Files) | 0 Groups (Member of 0 Groups)</p>

	</td>
	<td class="tdheaderright">
	</td>
	</tr>
	</table>
	</div><!--header-->
	
END_HTML

	#deal with error
	if(length($error_text) != 0){
		print "$error_text<br>";
	}
	
	#print remainder
	print <<END_HTML;
	<div class="content">
		<table>
			<form action="forgotPassword.pl.cgi" method=POST>
			<tr>
				<!-- username-->
				<td><p>Username:</p></td>
				<td><input type="text" name="username"></td>
			</tr>

			<tr>
				<!-- submit button-->
				<td><br /><input type="submit" value="Send Password"></form></td>
			</tr>		
		</table>
	</div><!--content-->
END_HTML

	#now call the subroutine to display the end of the html code
	HTMLSubs -> generate_html_end();
}

#subroutine to show that a password was successfully reset
sub show_success(){
	
	#call subroutine to generate html beginning
	HTMLSubs -> generate_html_beginning("Reset Password");

	#now print the message to the user
	print <<END_HTML;

	<div class="header">
	<div class="titles">
	<h1>Document Management System</h1>
	</div><!--titles-->

	<h2>Password Reset</h2>
	
	<!--now display the message to the user-->
	<h4>Your new password was emailed to the address you registered with our system. Please go to the profile to log in.</h4>
	<br>
	
	<form method="link" action="login.pl.cgi">
	<br>
	<input type="submit" value="Go to Login">
	</form>
END_HTML
	
	#now call the subroutine to display the end of the html code
	HTMLSubs -> generate_html_end();
}

#subroutine to regenerate and email the user his or her password
#this subroutine is passed the username as a parameter and then generates a new 8 character random password to be emailed to the user
sub regenerate_password{
	
	#declare array to hold all character possibilities
	my @chars=('a'..'z','A'..'Z','0'..'9','_');
	
	#obtain parameter
	my $username = $_[0];
	
	#now get information from DB
	my @info = DBQueries::getUserInfo($username);
	
	#create new empty string for password
	my $new_password = "";
	
	#loop to genreate random password
	for(my $i = 0; $i < 8; $i++){
		$new_password.=$chars[rand @chars];
	}
	
	#write new password to DB
	#therefore create md5
	my $hashed_password = md5_hex($new_password);
	
	#add to DB
	DBQueries::updateUserPassword($username, $hashed_password);
	
	#now send the email
	#proceed to use sendmail to send infomration to user
	#open mailhandle
	open(MAIL, "|/usr/sbin/sendmail -t");
	
	#send information to the mailhandler
	#start by sending the email header
	print MAIL "To: $info[2]\n";
	print MAIL "From: tr2286\@columbia.edu\n";
	print MAIL "Subject: Your New Password\n\n";

	#now send the testmessage
	print MAIL "Dear $username,\n";
	print MAIL "Your new password is $new_password\n";
	print MAIL "You can change this password at any time in your main profile.";
	print MAIL "We hope you enjoy this service!\nBest Regards,\nNathaniel Clinger and Thomas Rantasa";

	#cose the mailhandle
	close(MAIL);
}

#subroutine to obtain and determine what information is passed to the script
#to make this more universal, both GET and POST methods are accepted 
#this reads input for both GET and POST
sub obtain_input{

	#declare scalar to hold passed information
	my $input;

	#now retrieve the input through either get or post
	#change the case of request method
	$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

	#if post use STDIN
	if ($ENV{'REQUEST_METHOD'} eq "POST"){
		read(STDIN, $input, $ENV{'CONTENT_LENGTH'});

		#exchange plus signs to spaces
		$input =~ s/\+/ /;

		#deal with special characters using the substitution sample provided
		$input =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
	}
	#otherwise the env hash
	else{
		$input = $ENV{'QUERY_STRING'};
		
		#exchange plus signs to spaces
		$input =~ s/\+/ /;
		
		#deal with special characters using the substitution sample provided
		$input =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
	}
	
	#now return the correct input
	return $input;	
}

